<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>XG24-EK2703A板卡芯片温度变化曲线</title>
    <script type="text/javascript" src="jquery-3.2.0.min.js"></script>
    <script src="echarts.min.js"></script>
    <style>
      .button_group {
        position: fixed;
        top: 400px;
        left: 6%;
      }
      .button {
        width: 90px;
        height: 35px;
        border-width: 0px;
        border-radius: 3px;
        background: #1e90ff;
        cursor: pointer;
        outline: none;
        font-family: Microsoft YaHei;
        color: white;
        font-size: 15px;
      }
    </style>
  </head>
  <body>
    <div
      id="current_A"
      style="width: 600px; height: 400px; margin-bottom: 100px"
    ></div>

    <div class="button_group">
      <input
        class="button"
        type="button"
        value="读取"
        id="start"
        style="margin: 0 50px 0"
      />
      <input
        class="button"
        type="button"
        value="停止"
        id="stop"
        style="margin: 0 50px 0"
      />
    </div>
    <div>
      <pre>
        使用方法：
        1. 参考案例7+6，使用BLE UART发送温度数据，格式为：平均值,当前值\\n
        2. 安装 ble-serial: pip install ble-serial
        3. 安装 tornado: pip install tornado
        4. 执行 ble-scan，找到CIRCUITPY开头的设备对应的uuid
        5. 执行 ble-serial -d 设备对应的uuid --expose-tcp-host 127.0.0.1 --expose-tcp-port 9999
        6. 执行 python tcp_ws.py
        7. 执行 python -m http.server 9080
        8. 网页访问：http://127.0.0.1:9080/，点击读取
      </pre>
    </div>
    <script type="text/javascript">
      $(function () {
        var temp_real = 0;
        var temp_avg = 0;

        //判断浏览器是否支持WebSocket
        var supportsWebSockets =
          "WebSocket" in window || "MozWebSocket" in window;
        if (supportsWebSockets) {
          //建立WebSocket连接（ip地址换成自己主机ip）
          var ws = new WebSocket("ws://"+window.location.hostname+":9099/");
          ws.onopen = function () {
            //当WebSocket创建成功时，触发onopen事件
            console.log("websocket连接成功");
            // ws.send("hello"); //将消息发送到服务端
          };
          ws.onmessage = function (e) {
            //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
            console.log("收到数据");
            console.log(e.data);
            var tmp = String(e.data).replace(/[\s]/g, "").split(",");
            temp_avg = tmp[0];
            temp_real = tmp[1];
          };
          ws.onclose = function (e) {
            //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
            console.log("websocket已断开");
          };
          ws.onerror = function (e) {
            //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
            console.log("websocket发生错误" + e);
          };
        } else {
          layer.alert("您的浏览器不支持 WebSocket!");
        }

        // 初始化图表的数据输入数组
        var data_real = [];
        var data_avg = [];
        var data_length = 30;
        for (i = 0; i < data_length; i++) {
          data_avg.push(25);
          data_real.push(25);
        }

        //初始化全局变量
        var global_status = 0; //加载页面时默认为0

        //每个div分别创建一个form对象
        var CurrentA = new My_form("current_A");

        //页面加载时初始化静态图表
        CurrentA.init_static();

        //定义form类
        function My_form(element_id) {
          //form类所创建在指定的div的id
          this.element_id = element_id;

          //初始化图表，在具体指定元素位置创建图表，并传入数据列表
          this.init_static = function () {
            this.mychart = echarts.init(
              document.getElementById(this.element_id)
            );
            // 初始化x轴数据
            var _x_axis = [];
            for (var i = 0; i < data_length; i++) {
              _x_axis.push(i);
            }

            // 初始化y轴数据
            var real_arr = [];
            var avg_arr = [];
            for (var i = 0; i < data_length; i++) {
              real_arr.push(25);
              avg_arr.push(25);
            }

            //设置图标配置项
            this.mychart.setOption({
              title: {
                text: "XG24-EK2703A板卡芯片温度变化曲线",
                x: "left",
                textStyle: {
                  fontSize: 16,
                },
              },
              tooltip: {
                trigger: "axis",
              },
              // 调整图表在div中的大小
              grid: {
                top: "35px",
                left: "50px",
                right: "10px",
                bottom: "50px",
              },
              legend: {
                data: ["real", "avg"],
                textStyle: {
                  fontSize: getDpr(),
                },
                x: "center",
              },
              toolbox: {
                show: true,
                feature: {
                  mark: { show: true },
                  dataView: { show: true, readOnly: false },
                  magicType: { show: true, type: ["line"] },
                  saveAsImage: { show: true },
                },
              },
              calculable: true,
              xAxis: {
                type: "category",
                boundaryGap: false,
                data: _x_axis,
              },
              yAxis: {
                type: "value",
                min: 20,
                max: 30,
                splitNumber: 3,
              },
              series: [
                {
                  name: "当前值",
                  type: "line",
                  color: "red",
                  data: real_arr,
                },
                {
                  name: "平均值",
                  type: "line",
                  color: "green",
                  data: avg_arr,
                },
              ],
            });
          };

          // 更新数据函数
          this.update_data = function (real_data, model_data) {
            this.mychart.setOption({
              title: {
                text: "XG24-EK2703A板卡芯片温度变化曲线",
                x: "left",
                textStyle: {
                  fontSize: 16,
                },
              },
              series: [
                {
                  name: "当前值",
                  data: real_data,
                },
                {
                  name: "平均值",
                  data: model_data,
                },
              ],
            });
          };
        }

        //“开始实验”按钮点击事件
        $("input[id='start']").click(function () {
          global_status = 1;
        });

        //“终止实验”按钮点击事件
        $("input[id='stop']").click(function () {
          global_status = 0;
          data_real.fill(25);
          data_avg.fill(25);
          CurrentA.init_static();
        });

        //legend字体大小
        function getDpr() {
          var windowWidth = $(window).width();
          if (windowWidth < 1920) {
            return 12;
          }
          if (windowWidth >= 1920 && windowWidth <= 3840) {
            return 18;
          }
          if (windowWidth > 3840 && windowWidth <= 5760) {
            return 30;
          }
        }

        // 更新真实值
        function update_data() {
          data_real.push(temp_real);
          data_avg.push(temp_avg);
          if (data_real.length > data_length) {
            data_real.shift();
          }
          if (data_avg.length > data_length) {
            data_avg.shift();
          }
        }

        //设置监听函数每一秒一次
        setInterval(function () {
          if (global_status === 0) {
            return;
          }
          update_data();

          CurrentA.update_data(data_real, data_avg);
        }, 1000);
      });
    </script>
  </body>
</html>
